<?php
/**
 * easyThumbnail is a fork of cknight work. (thumbnail class)
 * You can read the original version here :
 * http://www.asp-php.net/ressources/bouts_de_code.aspx?id=465
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * PHP version required : (in theory)
 * jpeg, gif : PHP >= 4.0.6
 * png : PHP >= 4.3.2
 *
 * Check :
 * - jpeg : ok - quality : ok
 * - png : ok - quality : ok
 * - gif : to finish... - quality : none
 *
 * Todo :
 * gif : black becomes transparent when souce image is copied to thumbnail...
 *
 */

if (version_compare(PHP_VERSION, '5.1.0', '<'))
	exit('This version of easyThumbnail will only run on PHP version 5 or greater!');

if (! extension_loaded('gd') && ! extension_loaded('gd2'))
	exit('GD library don\'t exist');

class easyThumbnail {

	/**
	  * Quality of image reduced.
	  *
	  * @access protected
	  * @var int
	  */
	protected $quality = 70;

	/**
	  * Prefix to be added to the image name.
	  *
	  * @access protected
	  * @var string
	  */
	protected $prefix = 'tmb_';

	/**
	  * Size reduction of the thumbnail image. (in pixel)
	  *
	  * @access protected
	  * @var int
	  */
	protected $size = 60;

	/**
	  * File info of the original image. (dirname, basename, extension and filename)
	  * Note : The extension value is lowercase.
	  *
	  * @access protected
	  * @var array
	  */
	protected $fileInfo;

	/**
	  * Full name of the thumbnail image.
	  *
	  * @access protected
	  * @var string
	  */
	protected $thbName;

	/**
	  * Size of the original image.
	  *
	  * @access protected
	  * @var int
	  */
	protected $srcWidth, $srcHeight;

	/**
	  * Size of the thumbnail image.
	  *
	  * @access protected
	  * @var int
	  */
	protected $thbWidth, $thbHeight;

	/**
	  * Resource of the original image.
	  *
	  * @access protected
	  * @var resource
	  */
	protected $srcImg;

	/**
	  * Resource of the thumbnail image.
	  *
	  * @access protected
	  * @var resource
	  */
	protected $thbImg;

	/**
	  * Constructor.
	  *
	  * @access public
	  * @param string $image : Name of the source image with path
	  * @param string $destinationPath : Destination folder
	  * @return void
	  */
	public function __construct($image, $destinationPath) {
		if (! is_string($image))
			throw new Exception('$image attribute must be a string');

		if (! is_string($destinationPath))
			throw new Exception('$destinationPath attribute must be a string');

		if (! file_exists($image))
			throw new Exception('Source file of thumbnail don\' exist');

		$this->fileInfo = $this->getPathInfo($image);

		if (! in_array($this->fileInfo['extension'], array('jpg', 'jpeg', 'png', 'gif')))
			throw new Exception('Unauthorized file extension');

		if ('/' != substr($destinationPath, -1))
			$destinationPath = $destinationPath .'/';

		if (! is_dir($destinationPath))
			throw new Exception('Destination directory don\'t exist');

		$this->thbName		= $destinationPath . $this->prefix . $this->fileInfo['basename'];
		$this->srcImg		= $this->createThumbnailImage();
		$this->srcWidth		= (int) imagesx($this->srcImg);
		$this->srcHeight	= (int) imagesy($this->srcImg);
	}

	/**
	  * Set prefix thumbnail.
	  *
	  * @access public
	  * @param string $prefix : Prefix to be added to the image name.
	  * @return object : The easyThumbnail instance for chained methods.
	  */
	public function setPrefix($prefix) {
		if (is_string($prefix) && '' != $prefix)
			$this->prefix = $prefix;
		else
			throw new InvalidArgumentException('Prefix must be an string and not empty');

		return $this;
	}

	/**
	  * Set size of thumbnail.
	  *
	  * @access public
	  * @param string $size : Size reduction. (in pixel)
	  * @return object : The easyThumbnail instance for chained methods.
	  */
	public function setSize($size) {
		if (is_int($size) && 0 < $size && $size < $this->srcWidth && $size < $this->srcHeight)
			$this->size = $size;
		else
			throw new InvalidArgumentException('Size must be an integer et plus petite que l\'image');

		return $this;
	}

	/**
	  * Set quality of thumbnail.
	  *
	  * @access public
	  * @param string $quality : Quality of image reduced. (0 - 100)
	  * @return object : The easyThumbnail instance for chained methods.
	  */
	public function setQuality($quality) {
		if (is_int($quality) && 0 < $quality && 100 > $quality)
			$this->quality = $quality;
		else
			throw new InvalidArgumentException('Quality must be an integer and between 0 and 100');

		return $this;
	}

	/**
	  * Get the path + name of the resulting thumbnail image.
	  *
	  * @access public
	  * @param void
	  * @return string : The path of thumbnail.
	  */
	public function getThumbnailName() {
		return $this->thbName;
	}

	/**
	  * Returns the error if it has a.
	  *

	  * @access public
	  * @param void
	  * @return string : The error message
	  */
	public function getError() {
		return $this->error;
	}

	/**
	  * Generate the thumbnail image.
	  *
	  * @access public
	  * @param void
	  * @return void
	  */
	public function generate() {
		try {
			$this->resizeThumbnailImage($this->srcImg);

			if ('png' == $this->fileInfo['extension'])
				$this->addPngTransparencyBackground();
			elseif ('gif' == $this->fileInfo['extension'])
				$this->addGifTransparencyBackground();

			if (! $this->copyToThumbnail())
				throw new Exception('The original image was not copied to the thumbnail');

			if (! $this->writeThumbnailImage())
				throw new Exception('The thumbnail was not created');

			$this->destroyBuffer();
		} catch (Exception $e) {
			$this->destroyBuffer();
			throw $e;
		}
	}

	/**
	  * Get path information of image file.
	  *
	  * @access protected
	  * @param string $image : Name of the source image with path
	  * @return array : The file info : dirname, basename, extension and filename
	  */
	protected function getPathInfo($image) {
		$fileInfo = pathinfo($image);

		if (version_compare(PHP_VERSION, '5.2.0', '<'))
			$fileInfo['filename'] = substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '.'));

		$fileInfo['extension'] = strtolower($fileInfo['extension']);

		return $fileInfo;
	}

	/**
	  * Create a new thumbnail image from source image.
	  *
	  * @access protected
	  * @param void
	  * @return resource : Return an image identifier representing the image obtained from the given source image.
	  */
	protected function createThumbnailImage() {
		if ('jpg' == $this->fileInfo['extension'])
			$function = 'imagecreatefromjpeg';
		else
			$function = 'imagecreatefrom'. $this->fileInfo['extension'];

		$srcImg = $function($this->fileInfo['dirname'] . DIRECTORY_SEPARATOR . $this->fileInfo['basename']);

		if (false === $srcImg)
			throw new Exception('Source file is unreadable');

		return $srcImg;
	}

	/**
	  * Resize image if needed.
	  *
	  * @access protected
	  * @param void
	  * @return void
	  */
	protected function resizeThumbnailImage() {
		if (! is_int($this->size))
			throw new Exception('You must define a thumbnail size');

		if ($this->srcWidth < $this->size && $this->srcHeight < $this->size)
			throw new Exception('The original image is too small');

		if ($this->srcWidth < $this->srcHeight) {
			$this->thbHeight	= $this->size;
			$this->thbWidth		= ($this->srcWidth / $this->srcHeight) * $this->thbHeight;
		} else {
			$this->thbWidth		= $this->size;
			$this->thbHeight	= ($this->srcHeight / $this->srcWidth) * $this->thbWidth;
		}

		$this->thbImg = imagecreatetruecolor($this->thbWidth, $this->thbHeight);

		if (false === $this->thbImg)
			throw new Exception('The buffer was not created');
	}

	/**
	  *  Add transparency for png image.
	  *
	  * @access protected
	  * @param void
	  * @return void
	  */
	protected function addPngTransparencyBackground() {
		imagealphablending($this->thbImg, false);
		imagesavealpha($this->thbImg, true);

		$bg = imagecolorallocatealpha($this->thbImg, 255, 255, 255, 127);

		if (false === $bg)
			throw new Exception('Cannot Allocate a transparency background color for png thumbnail');

		imagefilledrectangle($this->thbImg, 0, 0, $this->thbWidth, $this->thbHeight, $bg);
	}

	/**
	  *  Add transparency for gif image.
	  *
	  * @access protected
	  * @param void
	  * @return void
	  */
	protected function addGifTransparencyBackground() {
		$bg = imagecolorallocate($this->thbImg, 0, 0, 0);

		if (false === $bg)
			throw new Exception('Cannot Allocate a background color for gif thumbnail');

		imagecolortransparent($this->thbImg, $bg);
	}

	/**
	  * Copy the source image to thumbnail image.
	  *
	  * @access protected
	  * @param void
	  * @return bool : The result status for copy original image to thumbnail.
	  */
	protected function copyToThumbnail() {
		return imagecopyresampled($this->thbImg, $this->srcImg, 0, 0, 0, 0, $this->thbWidth, $this->thbHeight, $this->srcWidth, $this->srcHeight);
	}

	/**
	  * Write the thumbnail image.
	  *
	  * @access protected
	  * @param resource void
	  * @return bool : The result of writting thumbnail.
	  */
	protected function writeThumbnailImage() {
		switch ($this->fileInfo['extension']) {
			case 'jpg' :
			case 'jpeg' :
				return imagejpeg($this->thbImg, $this->thbName, $this->quality);

			case 'png' :
				return imagepng($this->thbImg, $this->thbName, (9 - (($this->quality / 100) * 9)));

			case 'gif' :
				return imagegif($this->thbImg, $this->thbName);
		}
	}

	/**
	  * Destroy the buffer.
	  *
	  * @access protected
	  * @param resource void
	  * @return void
	  */
	protected function destroyBuffer() {
		if (is_resource($this->srcImg))
			imagedestroy($this->srcImg);

		if (is_resource($this->thbImg))
			imagedestroy($this->thbImg);
	}
















function is_ani($filename) {
    if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    //an animated gif contains multiple "frames", with each frame having a
    //header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2) {
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
   }

    fclose($fh);
    return $count > 1;
}
















}

?>
